package com.jackrain.nea.util;

import com.jackrain.nea.core.model.dao.UsersDAO;
import com.jackrain.nea.core.model.domain.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
import java.util.List;

/**
 * 修改数据库加密密文
 * Created by kunlun on 2016/7/26.
 */
@Component
public class UpdatePwdHash {

    @Autowired
    private UsersDAO usersDAO;

    public void getUpdatePwdHash(){
        List<Users> usersList = usersDAO.findAll();
        for(int i = 0;i<usersList.size();i++){
            String username = usersList.get(i).getName();
            String password = usersList.get(i).getPassword();
            String pwdbrand = usersList.get(i).getPwdrand();
            byte[] pwdbrandBytekey = pwdbrand.getBytes();
            if(username != null && password != null){
                try {
                    // DES算法要求有一个可信任的随机数源
                    SecureRandom sr = new SecureRandom();

                    DESKeySpec deskey = new DESKeySpec(pwdbrandBytekey);
                    // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
                    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
                    SecretKey key = keyFactory.generateSecret(deskey);
                    // 加密对象
                    Cipher cipher = Cipher.getInstance("DES");
                    cipher.init(Cipher.ENCRYPT_MODE, key, sr);
                    // 加密，并把字节数组编码成字符串
                    String passwordhash = new sun.misc.BASE64Encoder().encode(cipher.doFinal(password.getBytes()));
                    usersDAO.updatePassword(passwordhash,username,password);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }
}
